package com.travel.agent.controller;

import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.Objects;
import java.util.Optional;

@RestController
@RequestMapping("/chat")
public class ChatController {

//    @Autowired
//    private DeepSeekChatModel chatModel;
    @Autowired
    private OpenAiChatModel chatModel;

    @GetMapping("/resume")
    public String resume(@RequestParam(value = "msg") String msg) {
        Prompt prompt = new Prompt(new SystemMessage("你是故事大王，擅长讲修仙故事。"), new UserMessage(msg));
        ChatResponse chatResponse = chatModel.call(prompt);
        return chatResponse.getResult().getOutput().getText();
    }

    @GetMapping(value = "/resume/stream", produces = "text/plain;charset=UTF-8")
    public Flux<String> resumeStream(@RequestParam(value = "msg") String msg) {
        Prompt prompt = new Prompt();
        prompt.augmentSystemMessage(new SystemMessage("你是故事大王，擅长讲修仙故事。").getText());
        prompt.augmentUserMessage(new UserMessage("""
                <指令>给我讲一个修仙故事</指令>
                <要求>
                  1.输出思考过程,开始思考时先输出"<think>"标签,思考结束时一定要输出"</think>"标签
                  2.思考过程要包括"角色定位"、"情感定位"
                </要求>
                下面开始一步一步思考：
                """).getText());
        Flux<ChatResponse> rsp = Optional.ofNullable( chatModel.stream(prompt)).orElse(Flux.empty());
        return rsp.map(chatResponse -> {
            if (Objects.isNull(chatResponse) || Objects.isNull(chatResponse.getResult()) || Objects.isNull(chatResponse.getResult().getOutput())) {
                return "";
            }
            return Optional.ofNullable(chatResponse.getResult().getOutput().getText()).orElse("");
        });
    }

}
